package io.hepu.robotize.security;

import io.hepu.robotize.IConstant;
import io.hepu.robotize.IContext;
import io.hepu.robotize.auth.JRedis;
import io.hepu.robotize.auth.Jwts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Optional;

/**
 * 使用 @WebFilter 时需要确保主类上有 @ServletComponentScan 以启用扫描
 */
@WebFilter(filterName = "JwtFilter", urlPatterns = "/*")
public class JwtFilter implements Filter {
    static final Logger LOG = LoggerFactory.getLogger(JwtFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        LOG.debug("Request Servlet Path: {}", req.getServletPath());
        String authorization = req.getHeader(IConstant.AUTHORIZATION_HEADER);
        if (null != authorization && !authorization.isEmpty()) {
            String jwtToken = Jwts.trimScheme(authorization);
            if (Jwts.valid(jwtToken)) {
                Optional.ofNullable(Jwts.getSubject(jwtToken)).ifPresent(id -> tryRecache(id, jwtToken));
            }
        }
        chain.doFilter(request, response);
    }

    // Recache jwt token
    private void tryRecache(String uid, String token) {
        String cacheKey = IContext.getJwtCacheKey(uid);
        if (!JRedis.exists(cacheKey)) {
            JRedis.serialize(cacheKey, token, Jwts.ttl(token));
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
